package cloud.smalla.interceptor;



import cloud.smalla.utils.JwtUtils;
import cloud.smalla.utils.RedisUtils;
import cloud.smalla.vo.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.security.sasl.AuthenticationException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import static cloud.smalla.constant.RedisConstant.LOGIN_CODE_KEY;
import static cloud.smalla.constant.RedisConstant.LOGIN_KEY_TTL;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        //1.获取token
        String token = request.getHeader("token");

        //2.若没有token则直接放行
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }

        //3.解析token
        String username;
        try {
            Claims claims = JwtUtils.getClaimsByToken(token);
            username = claims.getSubject();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //4.从redis中获取对象
        String redisKey = LOGIN_CODE_KEY + username;
        LoginUser loginUser = (LoginUser) redisUtils.get(redisKey);
        if(Objects.isNull(loginUser)){
            //抛出用户未登录的异常
            throw new AuthenticationException("403");
        }

        //获取之后刷新redis中对象的有效期
        redisUtils.expire(redisKey,LOGIN_KEY_TTL, TimeUnit.SECONDS);

        //5.将用户信息存入SecurityContext中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //放行
        filterChain.doFilter(request,response);

    }
}
